<?php

namespace App\Models;

use Auth;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;

    protected $guarded = ['permissions', 'level'];


    protected $casts = [
        'pid' => 'integer',
        'homeshow' => 'boolean',
        'top' => 'boolean',
        'recommended' => 'boolean'
    ];
    protected $types = [1 => '普通栏目', 2 => '封面栏目', 3 => '单文章', 4 => '外部链接'];
    protected $structures = [1 => '列表圆形结构', 2 => '十字文字结构', 3 => '左右结构', 4 => '大图CARD结构', 5 => '方形图文结构'];

    protected $appends = ['permissions', 'typeTitle', 'level', 'structureTitle'];


    /**
     * 类型类型
     * @return string
     */
    public function getTypeTitleAttribute()
    {
        return $this->types[$this->type];
    }

    /**
     * 展示结构
     * @return string
     */
    public function getStructureTitleAttribute()
    {
        return $this->structures[$this->structure];
    }

    /**
     * 操作权限
     * @return bool[]
     * @throws BindingResolutionException
     */
    public function getPermissionsAttribute()
    {
        return [
            'create' => Auth::check() && Auth::user()->can('create', $this),
            'update' => Auth::check() && Auth::user()->can('update', $this),
            'delete' => Auth::check() && Auth::user()->can('delete', $this),
        ];
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }


    /**
     * 栏目层级
     * @return int
     */
    public function getLevelAttribute()
    {
        return count(explode('-', $this->path)) - 2;
    }


    /**
     * 关联模型
     * @return BelongsToMany
     */
    public function article()
    {
        return $this->belongsTo(Article::class);
    }

    /**
     * 父级栏目
     * @return BelongsTo
     */
    public function parent()
    {
        return $this->belongsTo(self::class, 'pid');
    }


    /**
     * 所有后代子孙栏目
     * @return mixed
     */
    public function getChildrensAttribute()
    {
        return self::where('path', 'like', $this->path . "-%")->get();
    }

    /**
     * 后一代栏目
     */
    public function nextNodes()
    {
        return $this->hasMany(self::class, 'pid', 'id');
    }


    /**
     * 文章关联
     * @return HasMany
     */
    public function contents()
    {
        return $this->hasMany(Content::class);
    }
}
